package handler

import (
	"art-man-sys/model"
	"github.com/gin-gonic/gin"
	"path/filepath"
	"strconv"
)

func Upload(c *gin.Context) {
	file, _ := c.FormFile("img")
	ext := filepath.Ext(file.Filename)
	if ext != ".png" && ext != ".jpg" && ext != ".pneg" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "图片格式不正确",
		})
		return
	}
	path := "static/img/" + file.Filename
	err := c.SaveUploadedFile(file, path)
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "上传失败",
		})
		return
	}
	url := "http://" + c.Request.Host + "/" + path
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "上传成功",
		"data": url,
	})
	return
}
func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	img := c.PostForm("img")
	if title == "" || content == "" || img == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "数据不能为空",
		})
		return
	}
	article := model.Article{
		Title:   title,
		Content: content,
		Img:     img,
	}
	err := model.DB.Create(&article).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
	})
	return
}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))

	offset := (page - 1) * size
	var count int64
	model.DB.Model(&model.Article{}).Count(&count)
	var article []model.Article
	err := model.DB.Offset(offset).Limit(size).Find(&article).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "获取列表失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "获取列表成功",
		"data": gin.H{
			"count":   count,
			"article": article,
		},
	})
	return
}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var article model.Article

	err := model.DB.Where("id = ?", id).First(&article).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": article,
	})
	return

}
